/**
 * 路由跳转权限
 */
import router from '@/router'
import VueCookies from 'vue-cookies'
import appStore from '@/store'
import constRouters from '@/router/constRouters'
import routes from '@/router/routes'
import { getUserMenuData } from './authentication'
import { RouteRecordRaw } from 'vue-router'

const cookie: any = VueCookies

const whiteList: Array<string> = constRouters.map((route) => route.path)

const routeArr: RouteRecordRaw[] = []

getUserMenuData().forEach((item) => {
  routeArr.push(...routes.filter((route) => route.name === item))
})

routeArr.forEach((route) => {
  router.addRoute(route)
})

constRouters.forEach((route) => {
  router.addRoute(route)
})

router.beforeEach((to, from, next) => {
  const isLogin = cookie.get('token') //获取本地存储的登陆信息

  if (to.meta.isNotShowLeft) {
    appStore.userStore.updateLogin(false)
  } else {
    appStore.userStore.updateLogin(true)
  }
  if (whiteList.indexOf(to.path) != -1) {
    // 登录状态不允许到的页面
    if (isLogin && ['/login', '/register'].includes(to.path)) {
      next({ path: from.path })
    } else {
      next()
    }
    return
  }
  // 登录状态
  if (!isLogin && to.path !== '/login') {
    next({ path: '/login' })
  } else {
    next()
  }
})